/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package at.irian.web.jsf.orchestra;

import org.apache.myfaces.orchestra.conversation.ConversationContext;
import org.apache.myfaces.orchestra.conversation.ConversationManager;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import java.util.logging.Logger;
import java.util.Map;

/**
 * @author Manfred Geiler
 * @author Gerhard Petracek
 */
public class TransactionTokenPhaseListener implements PhaseListener
{
    private static final long serialVersionUID = -404784913891323122L;

    private final static Logger LOG = Logger.getLogger(TransactionTokenPhaseListener.class.getName());

    public void afterPhase(PhaseEvent event)
    {
        FacesContext facesContext = event.getFacesContext();

        if (isTransactionTokenRequestParameterPresent(facesContext))
        {
            String requestToken = getTransactionTokenRequestParameter(facesContext);

            ConversationContext conversationContext = ConversationManager.getInstance().getCurrentConversationContext();

            if (conversationContext != null)
            {
                TransactionTokenContainer transactionTokenContainer = getTransactionTokenContainer(conversationContext);

                LOG.finest("Restore View token " + requestToken + " context: " + transactionTokenContainer);

                if (transactionTokenContainer != null)
                {
                    TransactionTokenHandler transactionTokenHandler = new TransactionTokenHandler();
                    switch (transactionTokenContainer.checkToken(requestToken))
                    {
                        case DOUBLE_SUBMIT_OR_RELOAD:
                            transactionTokenHandler.handleDoubleSubmitOrReload(facesContext);
                            break;
                        case BROWSER_BACK:
                            transactionTokenHandler.handleBrowserBack(facesContext);
                            break;
                        case UNKNOWN:
                            transactionTokenHandler.handleUnknownRequest(facesContext);
                            break;
                        default:
                            // nothing
                    }
                }
            }
        }
    }

    private TransactionTokenContainer getTransactionTokenContainer(ConversationContext conversationContext)
    {
        return (TransactionTokenContainer)conversationContext.getAttribute(TransactionTokenParameterProvider.class.getName());
    }

    private String getTransactionTokenRequestParameter(FacesContext facesContext)
    {
        return getRequestParameterMap(facesContext).get(TransactionTokenParameterProvider.TRANSACTION_TOKEN_REQUEST_PARAMETER);
    }

    private boolean isTransactionTokenRequestParameterPresent(FacesContext facesContext)
    {
        return getRequestParameterMap(facesContext).containsKey(TransactionTokenParameterProvider.TRANSACTION_TOKEN_REQUEST_PARAMETER);
    }

    private Map<String, String> getRequestParameterMap(FacesContext facesContext)
    {
        return facesContext.getExternalContext().getRequestParameterMap();
    }

    public void beforePhase(PhaseEvent event)
    {
        //TODO test it!
        TransactionTokenRequestHandler.init(event.getFacesContext());
    }

    public PhaseId getPhaseId()
    {
        return PhaseId.RESTORE_VIEW;
    }
}
